package ils.domain.model;

import ils.util.HibernateUtil;
import ils.util.Util;
import junit.framework.Assert;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: rejeevd
 * Date: 16/09/12
 * Time: 21:11
 * To change this template use File | Settings | File Templates.
 */
public class UserRepositoryTest
{

    @Test
    public void testCreateUser()
    {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        UserRepositoryImpl userRepository = new UserRepositoryImpl();
        userRepository.setSessionFactory(sessionFactory);
        Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
        User user = new User();
        user.setFirstName("create");
        user.setLastName("test");
        user.setEmail(Util.randomString(8) + "@ils.com");
        user.setPasswordHash(Util.md5("password"));
        Address address = new Address();
        address.setLine1("fdfdf");
        address.setLine2("ffff");
        user.setAddress(address);
        user = userRepository.createUser(user);
        transaction.commit();
        Assert.assertTrue(user.getId() != 0);
        Assert.assertTrue(user.getAddress().getId() != 0);
    }

    @Test
    public void testLogin()
    {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        UserRepositoryImpl userRepository = new UserRepositoryImpl();
        userRepository.setSessionFactory(sessionFactory);
        Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
        User user = userRepository.login("rejeev@ils.com", Util.md5("password"));
        transaction.commit();
        Assert.assertNotNull(user);
    }

    @Test
    public void testGet()
    {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        UserRepositoryImpl userRepository = new UserRepositoryImpl();
        userRepository.setSessionFactory(sessionFactory);
        Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
        User user = userRepository.getUser(1);
        Assert.assertNotNull(user.getAddress());
        Set<String> roles = user.getRoles();
        int numberOfRoles = roles.size();
        transaction.commit();
        Assert.assertEquals(1, numberOfRoles);
    }

}
